
package com.superyee.commonlib.utils;


import android.content.Context;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class StringUtil {

    /**
     * 将指定的字符串数组用指定的间隔符号拼接起来
     *
     * @param divider
     * @param params
     * @return
     */
    public static String formatStr(String divider, String... params) {
        if (params == null) {
            return "";
        }
        StringBuilder result = new StringBuilder();
        for (String param : params) {
            if (TextUtils.isEmpty(param)) {
                continue;
            }
            if (result.length() > 0) {
                result.append(divider).append(param);
            } else {
                result.append(param);
            }
        }
        return result.toString();
    }


    public static String parseMoney(double money) {
        return String.format("%.2f", money);
    }


    public static String double2Fromat(double value) {
        return String.format("%.2fkm", value);
    }

    public static String distance(String lat, String lng, double curlat, double curlng) {
        double lat1 = StringUtil.parseDouble(lat, curlat);
        double lng1 = StringUtil.parseDouble(lng, curlng);
        return double2Fromat(calculateLineDistance(lat1, lng1, curlat, curlng));
    }

    public static String distance(double lat, double lng, double curlat, double curlng) {
        return double2Fromat(calculateLineDistance(lat, lng, curlat, curlng));
    }

    private static double calculateLineDistance(double lat, double lng, double curlat, double curlng) {
        double dx = lng - curlng; // 经度差值
        double dy = lat - curlat; // 纬度差值
        double b = (lat + curlat) / 2.0; // 平均纬度
        double Lx = Math.toRadians(dx) * 6367000.0 * Math.cos(Math.toRadians(b)); // 东西距离
        double Ly = 6367000.0 * Math.toRadians(dy); // 南北距离
        return Math.sqrt(Lx * Lx + Ly * Ly) / 1000;  // 用平面的矩形对角距离公式计算总距离
//
//        double var4 = lng;
//        double var6 = lat;
//        double var8 = curlng;
//        double var10 = curlat;
//        var4 *= 0.01745329251994329D;
//        var6 *= 0.01745329251994329D;
//        var8 *= 0.01745329251994329D;
//        var10 *= 0.01745329251994329D;
//        double var12 = Math.sin(var4);
//        double var14 = Math.sin(var6);
//        double var16 = Math.cos(var4);
//        double var18 = Math.cos(var6);
//        double var20 = Math.sin(var8);
//        double var22 = Math.sin(var10);
//        double var24 = Math.cos(var8);
//        double var26 = Math.cos(var10);
//        double[] var28 = new double[3];
//        double[] var29 = new double[3];
//        var28[0] = var18 * var16;
//        var28[1] = var18 * var12;
//        var28[2] = var14;
//        var29[0] = var26 * var24;
//        var29[1] = var26 * var20;
//        var29[2] = var22;
//        double var30 = Math.sqrt((var28[0] - var29[0]) * (var28[0] - var29[0]) + (var28[1] - var29[1]) * (var28[1] - var29[1]) + (var28[2] - var29[2]) * (var28[2] - var29[2]));
//        return (Math.asin(var30 / 2.0D) * 1.27420015798544E7D / 1000);
    }

    /**
     * Native to ascii string. It's same as execut native2ascii.exe.
     *
     * @param str native string
     * @return ascii string
     */
    public static String native2Ascii(String str) {
        char[] chars = str.toCharArray();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < chars.length; i++) {
            sb.append(char2Ascii(chars[i]));
        }
        return sb.toString();
    }

    /**
     * Native character to ascii string.
     *
     * @param c native character
     * @return ascii string
     */
    private static String char2Ascii(char c) {
        if (c > 255) {
            StringBuilder sb = new StringBuilder();
            sb.append("\\u");
            int code = (c >> 8);
            String tmp = Integer.toHexString(code);
            if (tmp.length() == 1) {
                sb.append("0");
            }
            sb.append(tmp);
            code = (c & 0xFF);
            tmp = Integer.toHexString(code);
            if (tmp.length() == 1) {
                sb.append("0");
            }
            sb.append(tmp);
            return sb.toString();
        } else {
            return Character.toString(c);
        }
    }

    /**
     * Ascii to native string. It's same as execut native2ascii.exe -reverse.
     *
     * @param str ascii string
     * @return native string
     */
    public static String ascii2Native(String str) {
        StringBuilder sb = new StringBuilder();
        int begin = 0;
        int index = str.indexOf("\\u");
        while (index != -1) {
            sb.append(str.substring(begin, index));
            sb.append(ascii2Char(str.substring(index, index + 6)));
            begin = index + 6;
            index = str.indexOf("\\u", begin);
        }
        sb.append(str.substring(begin));
        return sb.toString();
    }

    /**
     * Ascii to native character.
     *
     * @param str ascii string
     * @return native character
     */
    private static char ascii2Char(String str) {
        if (str.length() != 6) {
            throw new IllegalArgumentException(
                    "Ascii string of a native character must be 6 character.");
        }
        if (!"\\u".equals(str.substring(0, 2))) {
            throw new IllegalArgumentException(
                    "Ascii string of a native character must start with \"\\u\".");
        }
        String tmp = str.substring(2, 4);
        int code = Integer.parseInt(tmp, 16) << 8;
        tmp = str.substring(4, 6);
        code += Integer.parseInt(tmp, 16);
        return (char) code;
    }

    /**
     * 转换 url, 返回宽为 120 像素的缩略图的 url
     */
    public static String toThumbUrl(String imageUrl) {
        final String url = imageUrl;
        try {
            if (!TextUtils.isEmpty(imageUrl)) {
                String[] datas = url.split("_");
                if (datas != null && datas.length == 3) {
                    String numberFormat = datas[1];
                    if (!TextUtils.isEmpty(numberFormat)) {
                        String[] numbers = numberFormat.split("-");
                        if (numbers != null && numbers.length == 2) {
                            StringBuilder sb = new StringBuilder();
                            sb.append(datas[0]);
                            sb.append("_");
                            sb.append("120" + "-" + numbers[1]);
                            sb.append("_");
                            sb.append(datas[2]);
                            return sb.toString();
                        }
                    }
                }
            }
        } catch (Exception e) {
        }
        return url;
    }

    /**
     * String转Int
     */
    public static int parseInt(String str, int defaultValue) {
        try {
            return (int) parseDouble(str, defaultValue);
        } catch (Exception e) {
            return defaultValue;
        }
    }

    public static int parseInt(Object obj, int defaultValue) {
        try {
            return Integer.parseInt(String.valueOf(obj));
        } catch (Exception e) {
            return defaultValue;
        }
    }

    /**
     * String转long
     */
    public static long parseLong(String str, long defaultValue) {
        try {
            return Long.parseLong(str);
        } catch (Exception e) {
            return defaultValue;
        }
    }

    /**
     * String 转 float
     */
    public static float parseFloat(String str, float defaultValue) {
        try {
            return Float.parseFloat(str);
        } catch (Exception e) {
            return defaultValue;
        }
    }

    /**
     * String 转 double
     */
    public static double parseDouble(String str, double defaultValue) {
        try {
            return Double.parseDouble(str);
        } catch (Exception e) {
            return defaultValue;
        }
    }

    /**
     * 将小数点转化为百分比
     */
    public static String dotToPercent(String value) {
        String percent = "";
        float fValue;
        try {
            fValue = Float.parseFloat(value);
            percent = fValue * 100 + "%";
        } catch (Exception e) {
            percent = "0%";
        }
        return percent;
    }

    /**
     * 判断是否是手机号码
     */
    public static boolean isPhoneNumber(String num) {
        // String reg2 =
        // "^((861)|(00861)|(\\+861)|1)((3[0-9])|(5[0-3|5-9])|(8[5-9])|82|47|80)[0-9]{8}$";
//		String reg = "^((86)|(086)|(0086)|(\\+86)){0,1}((13[0-9])|(15[^4,\\D])|(14[0-9])|(17[0-9])|(18[0-9]))\\d{8}$";
//		return !TextUtils.isEmpty(num) ? num.matches(reg) : false;
        if (num != null && num.length() == 11 && num.startsWith("1")) {
            return true;
        }
        return false;
    }

    /**
     * 判断字符串 去掉空格符后 是否是空值，
     *
     * @param value
     * @return
     */
    public static boolean isEmpty(String value) {
        if (TextUtils.isEmpty(value)
                || "NULL".equalsIgnoreCase(value)) {
            return true;
        } else {
            return value.trim().length() == 0;
        }
    }


    /**
     * 去除字符串中的空格、回车、换行符、制表符、间隔线
     */
    public static String replaceBlank(String str) {
        String dest = "";
        if (str != null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n|-");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }


    /**
     * 判断list是否有效
     */
    public static <T> boolean isListValidate(List<T> list) {
        if (list != null && list.size() > 0) {
            return true;
        }
        return false;
    }

    public static String uuid() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    public static byte[] InputStreamToByte(InputStream is) throws IOException {
        ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
        int ch;
        while ((ch = is.read()) != -1) {
            bytestream.write(ch);
        }
        byte imgdata[] = bytestream.toByteArray();
        bytestream.close();
        return imgdata;
    }

    public String inputStream2String(InputStream in) {
        StringBuffer out = new StringBuffer();
        byte[] b = new byte[4096];
        int n;
        try {
            while ((n = in.read(b)) != -1) {
                out.append(new String(b, 0, n));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return out.toString();
    }


    public static String repString(String str) {
        return str.replaceAll("\\\\", "\\");
    }

    /**
     * 判断字符串是否为空或null
     *
     * @return
     */
    public static String getText(String text) {
        if (text == null) {
            return "";
        }
        if (text.trim().equalsIgnoreCase("NULL") || text.trim().equals("")) {
            return "";
        }
        return text;
    }


    /**
     * 去除手机号中间的-,+和空格
     *
     * @param number
     * @return
     */
    public static String formatNumber(String number) {
        if (StringUtil.isEmpty(number)) {
            return "";
        }
        return number.replace("-", "").replace("+", "").replace(" ", "");
    }

    /**
     * 号码格式标准化<br>
     * "00"+国家码+"裸号"
     *
     * @param number
     * @return
     */
    public static String formatNumber(String number, Context context) {
        String ccode = getCountryCode(context);
        if (!StringUtil.isEmpty(number)) {
            number.replace("-", "");
            if (number.startsWith("00")) {
                return "+" + number.substring(2);
            } else if (number.startsWith("0")) {
                return "+" + number.substring(1);
            } else if (number.startsWith("+")) {
                return number;
            } else if (number.startsWith(ccode)) {
                return "+" + number;
            } else {
                return "+" + ccode + number;
            }
        }
        return "";
    }

    /**
     * 获取国家码
     *
     * @return
     */
    public static String getCountryCode(Context context) {
        String COUNTRY_CODE = null;
        if (COUNTRY_CODE == null || COUNTRY_CODE.length() < 1) {
            TelephonyManager tm = (TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE);
            String cc = tm.getSimCountryIso();
            // 这里只是强制换位中国的，模拟器是美国的。
            cc = "cn";
            if (cc.startsWith("+")) {
                COUNTRY_CODE = cc.substring(1);
            } else {
                if (cc.equalsIgnoreCase("fr")) {
                    COUNTRY_CODE = "33";
                } else if (cc.equalsIgnoreCase("cn")) {
                    COUNTRY_CODE = "86";
                } else if (cc.equalsIgnoreCase("es")) {
                    COUNTRY_CODE = "34";
                } else if (cc.equalsIgnoreCase("fi")) {
                    COUNTRY_CODE = "358";
                } else if (cc.equalsIgnoreCase("us")) {
                    COUNTRY_CODE = "1";
                } else {
                    COUNTRY_CODE = "86";
                }
            }
        }
        return COUNTRY_CODE;
    }

}
